package com.miracle.yuanshen;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Environment;


public class JsonUtils {

    private static File CacheRoot;

    /**
     * 存储Json文件
     *
     * @param context
     * @param json
     *            json字符串
     * @param fileName
     *            存储的文件名
     * @param append
     *            true 增加到文件末，false则覆盖掉原来的文件
     */
    public static void writeJson(Context context, String json, String fileName,
                                 boolean append) {

        CacheRoot = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? context
                .getExternalCacheDir() : context.getCacheDir();
        FileOutputStream fos = null;
        try {
            File ff = new File(CacheRoot, fileName);
            boolean boo = ff.exists();
            fos = new FileOutputStream(ff, append);
            fos.write(json.getBytes("UTF_8"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取json数据
     *
     * @param c
     * @param fileName
     * @return 返回值为list
     */

    @SuppressWarnings("resource")
    public static String readJson(Context c, String fileName) {

        CacheRoot = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? c
                .getExternalCacheDir() : c.getCacheDir();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        List<String> result = new ArrayList<String>();
        File des = new File(CacheRoot, fileName);

        String str = null;
        try {
            fis = new FileInputStream(des);
            int length = fis.available();
            byte bytes[] = new byte[length];
            fis.read(bytes);
            fis.close();
            str = new String(bytes, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }


        return str;
    }

}
